package com.qiwenshare.file.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiwenshare.common.anno.MyLog;
import com.qiwenshare.common.result.RestResult;
import com.qiwenshare.common.util.DateUtil;
import com.qiwenshare.common.util.HashUtils;
import com.qiwenshare.common.util.security.JwtUser;
import com.qiwenshare.common.util.security.SessionUtil;
import com.qiwenshare.file.api.IUserLoginInfoService;
import com.qiwenshare.file.api.IUserService;
import com.qiwenshare.file.component.JwtComp;
import com.qiwenshare.file.dingding.api.DingdingOldSdkApi;
import com.qiwenshare.file.domain.UserLoginInfo;
import com.qiwenshare.file.domain.user.UserBean;
import com.qiwenshare.file.dto.user.RegisterDTO;
import com.qiwenshare.file.vo.user.UserLoginVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;


@Tag(name = "user", description = "该接口为用户接口，主要做用户登录，注册和校验token")
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Value("${dingding.agent.agentName}")
    public String agentName;
    @Autowired
    private DingdingOldSdkApi dingdingOldSdkApi;
    @Resource
    IUserService userService;
    @Resource
    IUserLoginInfoService userLoginInfoService;
    @Resource
    JwtComp jwtComp;

    public static Map<String, String> verificationCodeMap = new HashMap<>();
    public static final String CURRENT_MODULE = "用户管理";

      //private  static String url="http://127.0.0.1:8087";//本地
     private  static String url="http://110.81.207.46:8087";//测试服务器
    //private  static String url="http://120.79.244.220:8080";//正式服务器



    @Operation(summary = "用户注册", description = "注册账号", tags = {"user"})
    @PostMapping(value = "/register")
    @MyLog(operation = "用户注册", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> addUser(@Valid @RequestBody RegisterDTO registerDTO) {
        RestResult<String> restResult = null;
        UserBean userBean = new UserBean();
        BeanUtil.copyProperties(registerDTO, userBean);
        restResult = userService.registerUser(userBean);

        return restResult;
    }

    @Operation(summary = "用户登录", description = "用户登录认证后才能进入系统", tags = {"user"})
    @GetMapping("/login")
    @MyLog(operation = "用户登录", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<UserLoginVo> userLogin(
            @Parameter(description = "登录手机号") String telephone,
            @Parameter(description = "登录密码") String password){
        RestResult<UserLoginVo> restResult = new RestResult<UserLoginVo>();
        String salt = userService.getSaltByTelephone(telephone);
        String hashPassword = HashUtils.hashHex("MD5", password, salt, 1024);
        UserBean result = userService.selectUserByTelephoneAndPassword(telephone, hashPassword);
        if (result == null) {
            return RestResult.fail().message("手机号或密码错误！");
        }

        Map<String, Object> param = new HashMap<>();
        param.put("userId", result.getUserId());
        String token = "";
        try {
            token = jwtComp.createJWT(param);
        } catch (Exception e) {
            log.info("登录失败：{}", e);
            return RestResult.fail().message("创建token失败！");
        }
        UserBean sessionUserBean = userService.findUserInfoByTelephone(telephone);
        if (sessionUserBean.getAvailable() != null && sessionUserBean.getAvailable() == 0) {
            return RestResult.fail().message("用户已被禁用");
        }
        UserLoginVo userLoginVo = new UserLoginVo();
        BeanUtil.copyProperties(sessionUserBean, userLoginVo);
        userLoginVo.setToken("Bearer " + token);
        restResult.setData(userLoginVo);
        restResult.setSuccess(true);
        restResult.setCode(200001);
        return restResult;
    }



    @Operation(summary = "检查用户登录信息", description = "验证token的有效性", tags = {"user"})
    @GetMapping("/checkuserlogininfo")
    @ResponseBody
    public RestResult<UserLoginVo> checkUserLoginInfo(@RequestHeader("token") String token) {
        UserLoginVo userLoginVo = new UserLoginVo();
        String userId = userService.getUserIdByToken(token);

        if (StringUtils.isNotEmpty(userId)) {
            LambdaQueryWrapper<UserLoginInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserLoginInfo::getUserId, userId);
            lambdaQueryWrapper.likeRight(UserLoginInfo::getUserloginDate, DateUtil.getCurrentTime().substring(0, 10));
            userLoginInfoService.remove(lambdaQueryWrapper);
            UserLoginInfo userLoginInfo = new UserLoginInfo();
            userLoginInfo.setUserId(userId);
            userLoginInfo.setUserloginDate(DateUtil.getCurrentTime());
            userLoginInfoService.save(userLoginInfo);
            UserBean user = userService.getById(userId);
            BeanUtil.copyProperties(user, userLoginVo);
            if (StringUtils.isEmpty(user.getWxOpenId())) {
                userLoginVo.setHasWxAuth(false);
            } else {
                userLoginVo.setHasWxAuth(true);
            }
            return RestResult.success().data(userLoginVo);

        } else {
            return RestResult.fail().message("用户暂未登录");
        }
    }

    ////swq20240223 改造扫描登录
    @Operation(summary = "用户登录", description = "用户登录认证后才能进入系统", tags = {"user"})
    @GetMapping("/loginScan")
    @MyLog(operation = "用户登录", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<UserLoginVo> userLoginScan(@Parameter(description = "登录手机号") String accessToken){

        JSONObject jsobj1 = new JSONObject();
        jsobj1.put("test","");
        String returnStr = post(jsobj1, url+"/taccountScanLogin/getAccessTokenUser?accessToken="+accessToken);
        JSONObject data = JSONObject.parseObject(returnStr);
        String  isExistUser=data.getString("isExistUser");//0:存在可用用户;1:不存在用户
        String  username=data.getString("username");
        if(isExistUser.equals("0")) {
            String telephone = username;
            RestResult<UserLoginVo> restResult = new RestResult<UserLoginVo>();
            String salt = userService.getSaltByTelephone(telephone);
            UserBean result = userService.findUserInfoByTelephone(telephone);
            if (result == null) {
                return RestResult.fail().message("当前账号:" + telephone + "不存在,不能登录图片管理系统");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("userId", result.getUserId());
            String token = "";
            try {
                token = jwtComp.createJWT(param);
            } catch (Exception e) {
                log.info("登录失败：{}", e);
                return RestResult.fail().message("创建token失败！");
            }
            UserBean sessionUserBean = userService.findUserInfoByTelephone(telephone);
            if (sessionUserBean.getAvailable() != null && sessionUserBean.getAvailable() == 0) {
                return RestResult.fail().message("用户已被禁用");
            }
            UserLoginVo userLoginVo = new UserLoginVo();
            BeanUtil.copyProperties(sessionUserBean, userLoginVo);
            userLoginVo.setToken("Bearer " + token);
            userLoginVo.setAccessToken(accessToken);
            restResult.setData(userLoginVo);
            restResult.setSuccess(true);
            restResult.setCode(200001);
            return restResult;
        }
        else
        {
            return RestResult.fail().message("当前accessToken不可用,不存在关联账号！");
        }
    }


    @Operation(summary = "检查用户登录信息", description = "验证token的有效性", tags = {"user"})
    @GetMapping("/checkuserlogininfoScan")
    @ResponseBody
    public RestResult<UserLoginVo> checkUserLoginInfoScan(@RequestHeader("token") String token) {

        UserLoginVo userLoginVo = new UserLoginVo();
        String userId = userService.getUserIdByToken(token);
        if (StringUtils.isNotEmpty(userId)) {
            LambdaQueryWrapper<UserLoginInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserLoginInfo::getUserId, userId);
            lambdaQueryWrapper.likeRight(UserLoginInfo::getUserloginDate, DateUtil.getCurrentTime().substring(0, 10));
            userLoginInfoService.remove(lambdaQueryWrapper);
            UserLoginInfo userLoginInfo = new UserLoginInfo();
            userLoginInfo.setUserId(userId);
            userLoginInfo.setUserloginDate(DateUtil.getCurrentTime());
            userLoginInfoService.save(userLoginInfo);
            UserBean user = userService.getById(userId);
            BeanUtil.copyProperties(user, userLoginVo);
            if (StringUtils.isEmpty(user.getWxOpenId())) {
                userLoginVo.setHasWxAuth(false);
            } else {
                userLoginVo.setHasWxAuth(true);
            }
            return RestResult.success().data(userLoginVo);

        } else {
            return RestResult.fail().message("用户暂未登录");
        }
    }

    public static String post(JSONObject json, String url) {
        String result="";
        try {
            HttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost(url);
            post.setHeader("Content-Type", "appliction/json");
            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity s=new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "appliction/json"));
            post.setEntity(s);
            HttpResponse httpResponse=client.execute(post);
            InputStream in=httpResponse.getEntity().getContent();
            BufferedReader br=new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber=new StringBuilder();
            String line=null;
            while ((line=br.readLine())!=null) {
                strber.append(line+"\n");
            }
            in.close();
            result=strber.toString();
            if(httpResponse.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
                result="服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }
        System.out.println("result=="+result);
        return result;
    }

    //swq20240223   改造扫码登录






    @Operation(summary = "检查微信认证", description = "检查微信认证", tags = {"user"})
    @GetMapping("/checkWxAuth")
    @ResponseBody
    public RestResult<Boolean> checkWxAuth() {
        JwtUser sessionUserBean = SessionUtil.getSession();
        if (sessionUserBean != null && !"anonymousUser".equals(sessionUserBean.getUsername())) {
            UserBean user = userService.getById(sessionUserBean.getUserId());

            if (StringUtils.isEmpty(user.getWxOpenId())) {
                return RestResult.success().data(false);
            } else {
                return RestResult.success().data(true);
            }

        } else {
            return RestResult.fail().message("用户暂未登录");
        }

    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @RequestMapping(value="/dingLogin")
    public RestResult<UserLoginVo> dingLogin(@RequestParam(value = "authCode") String code) throws Exception {
        String me = dingdingOldSdkApi.getAuthAccessToken(agentName, code);
        String unionId = JSON.parseObject(me).getString("unionId");
        String ddUserId = dingdingOldSdkApi.getUserIdByUnionId(unionId);
        UserBean sysUser = userService.findUserByDDUserId(ddUserId);
        if (sysUser == null) {
            return RestResult.fail().message("用户不存在！");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("userId", sysUser.getUserId());
        String token = "";
        try {
            token = jwtComp.createJWT(param);
        } catch (Exception e) {
            log.info("登录失败：{}", e);
            return RestResult.fail().message("创建token失败！");
        }
        if (sysUser.getAvailable() != null && sysUser.getAvailable() == 0) {
            return RestResult.fail().message("用户已被禁用");
        }
        RestResult<UserLoginVo> restResult = new RestResult<UserLoginVo>();
        UserLoginVo userLoginVo = new UserLoginVo();
        BeanUtil.copyProperties(sysUser, userLoginVo);
        userLoginVo.setToken("Bearer " + token);
        restResult.setData(userLoginVo);
        restResult.setSuccess(true);
        restResult.setCode(200001);
        System.out.println("restResult:"+restResult);

        return restResult;
    }

}
